package com.example.springbootoauth2jwtclientserver.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

@Service(value = "rbacService")
public class CustomRbacService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public Boolean hasPermission(HttpServletRequest request, Authentication authentication){
        Object principal = authentication.getPrincipal();
        String username;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        }else if(principal instanceof DefaultOAuth2User){
            username = ((DefaultOAuth2User) principal).getName();
        }else{
            username = principal.toString();
        }

        boolean hasPermission = false;
        if (StringUtils.hasText(username) && !"anonymousUser".equals(username)) {
            Set<String> uris = new HashSet<>();
            for (String uri : uris) {
                if (antPathMatcher.match(uri,request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
            return true;
        }
        return hasPermission;
    }
}
